import axios from "axios";

/**
 *  修改数据的请求
 * @param {*} info 一些响应式对象
 * @param {*} router 路由函数
 */
export default function submitData(user_id, info) {
  info;
  /**
   * 根据 article_id 更新
   * @param {*} article_id
   * @param {*} article
   * @returns
   */
  const update_article = (article_id, article) => {
    return updateContent(article_id, article, "articles");
  };
  const delete_article = (article_id) => {
    return deleteContent(article_id, "articles");
  };
  const create_article = (article) => {
    return createContent(user_id, article, "articles");
  };

  const update_badge = (badge_id, badge) => {
    return updateContent(badge_id, badge, "badges");
  };
  const create_badge = (badge) => {
    return createContent(user_id, badge, "badges");
  };

  const update_collcetion = (collecion_id, collection) => {
    return updateContent(collecion_id, collection, "collections");
  };
  const create_collection = (collection) => {
    return createContent(user_id, collection, "collections");
  };
  const update_essay = (essay_id, essay) => {
    return updateContent(essay_id, essay, "essays");
  };
  const delete_essay = (essay_id) => {
    return deleteContent(essay_id, "essays");
  };
  const create_essay = (essay) => {
    return createContent(user_id, essay, "essays");
  };

  return {
    update_article,
    delete_article,
    create_article,

    update_essay,
    delete_essay,
    create_essay,

    update_badge,
    create_badge,

    update_collcetion,
    create_collection,
  };
}

const updateContent = (id, content, type) => {
  return new Promise((resolve, reject) => {
    axios
      .patch(`/api/${type}/${id}/`, content.value)
      .then(function (response) {
        content.value = response.data;
        resolve(response.data);
      })
      .catch(function (error) {
        reject(error);
      })
      .then(function () {
        // 总是会执行
      });
  });
};

const deleteContent = (id, type) => {
  return new Promise((resolve, reject) => {
    axios
      .delete(`/api/${type}/${id}/`)
      .then(function (response) {
        resolve(response.data);
      })
      .catch(function (error) {
        reject(error);
      })
      .then(function () {
        // 总是会执行
      });
  });
};

const createContent = (user_id, content, type) => {
  return new Promise((resolve, reject) => {
    axios
      .post(`/api/${type}/`, {
        ...content.value,
        author: user_id,
      })
      .then(function (response) {
        resolve(response.data);
      })
      .catch(function (error) {
        reject(error);
      })
      .then(function () {
        // 总是会执行
      });
  });
};
